/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package flp.gui.listener;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JTextField;

/**
 *
 * @author marek
 */
public class DoubleFieldFocusListener extends FocusAdapter
{
    private Double greaterThen;
    private Double greaterEqual;
    private Double lessThen;
    private Double lessEqual;
    private double precision = 0.001;
    
    @Override
    public void focusGained(FocusEvent e)
    {
        JTextField textField = (JTextField)e.getSource();
        textField.selectAll();
    }

    @Override
    public void focusLost(FocusEvent e)
    {
        JTextField textField = (JTextField)e.getSource();
        String content = textField.getText();
        if (content.length() == 0)
        {
            content = "0.0";
        }

        try
        {
            double number = Double.parseDouble(content);
            number = correct(number);
            textField.setText(Double.toString(number));
        }
        catch (NumberFormatException nfe)
        {
            System.err.println(nfe.getStackTrace());
            textField.requestFocusInWindow();
        }
    }
    
    public void setPrecision(double precision)
    {
        this.precision = precision;
    }
    
    private double correct(double input)
    {
        if (null != greaterThen)
        {
            input = input > greaterThen ? input : greaterThen + precision;
        }
        else if (null != greaterEqual)
        {
            input = input >= greaterThen ? input : greaterEqual;
        }
        
        if (null != lessThen)
        {
            input = input < lessThen ? input : lessThen - precision;
        }
        else if (null != lessEqual)
        {
            input = input <= lessEqual ? input : lessEqual;
        }
        
        return input;
    }
    
    public DoubleFieldFocusListener setGreaterThen(double gt)
    {
        greaterEqual = null;
        greaterThen = gt;
        return this;
    }
    
    public DoubleFieldFocusListener setGreaterEqual(double ge)
    {
        greaterThen = null;
        greaterEqual = ge;
        return this;
    }
    
    public DoubleFieldFocusListener setLessThen(double lt)
    {
        lessEqual = null;
        lessThen = lt;
        return this;
    }
    
    public DoubleFieldFocusListener setLessEqual(double le)
    {
        lessThen = null;
        lessEqual = le;
        return this;
    }
}
